package com.cxx.food.service.impl;


import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cxx.food.dto.SessionDto;
import com.cxx.food.dto.UserDto;
import com.cxx.food.entity.User;
import com.cxx.food.mapper.UserMapper;
import com.cxx.food.service.SessionService;
import com.cxx.framework.web.CustomException;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


@Service
public class SessionServiceImpl implements SessionService {
    @Resource
    private UserMapper userMapper;

    @Override
    public SessionDto create(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new CustomException("该用户不存在");
        }

        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new CustomException("密码不正确");
        }

        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);

        SessionDto sessionDto = new SessionDto();
        StpUtil.login(user.getId());
        sessionDto.setSaToken(StpUtil.getTokenInfo());
        sessionDto.setUserInfo(userDto);

        return sessionDto;
    }

    @Override
    public Boolean abort(String username) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new CustomException("该用户不存在");
        }

        StpUtil.logout(user.getId());

        return Boolean.TRUE;
    }
}
